<!--
 厦门大学计算机专业 | 前华为工程师
 专注《零基础学编程系列》https://cxyxy.blog.csdn.net/article/details/121134634
 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 公众号：蓝不蓝编程
-->
<template>
  <div class="container">
    <div>
      <span class="display-time">{{ displayTime }}</span>
    </div>

    <div class="button-container">
      <el-button type="info" @click="resetTimer">重置</el-button>
      <el-button type="primary" @click="startOrPauseTimer">{{
        startPauseButtonText
      }}</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HspPage',
  data() {
    return {
      startPauseButtonText: '开始',
      displayTime: '00:00:000',
      isStarted: false,
      lastTimeElapsed: 0,
      interval: 0,
      startTime: Date.now()
    }
  },
  methods: {
    startOrPauseTimer() {
      if (this.isStarted) {
        if (this.interval !== 0) {
          clearInterval(this.interval)
          this.interval = 0
        }
        this.lastTimeElapsed =
          Date.now() - this.startTime + this.lastTimeElapsed
        this.startPauseButtonText = '开始'
      } else {
        this.startTime = Date.now()
        this.startPauseButtonText = '暂停'

        if (this.interval === 0) {
          this.interval = setInterval(() => {
            var timeOffset = Date.now() - this.startTime + this.lastTimeElapsed
            this.displayTime = this.formatTime(timeOffset)
          }, 100)
        }
      }

      this.isStarted = !this.isStarted
    },
    resetTimer() {
      if (this.interval !== 0) {
        clearInterval(this.interval)
        this.interval = 0
      }
      this.displayTime = this.formatTime(0)
      this.isStarted = false
      this.lastTimeElapsed = 0
      this.startPauseButtonText = '开始'
    },
    formatTime(timeOffset) {
      var mm = parseInt(timeOffset / 1000 / 60)
      if (mm < 10) mm = '0' + mm
      var ss = parseInt((timeOffset / 1000) % 60)
      if (ss < 10) ss = '0' + ss
      var ssss = parseInt(timeOffset % 1000)
      if (ssss < 10) {
        ssss = '00' + ssss
      } else if (ssss < 100) {
        ssss = '0' + ssss
      }
      return `${mm}:${ss}:${ssss}`
    }
  }
}
</script>

<style scoped>
.display-time {
  color: white;
  font-size: 3.4em;
  align-self: center;
}
.button-container {
  padding-top: 10rem;
}
</style>
